import "dart:convert";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/associate_room/index.dart";
import "package:ct_pa_majordomo/pages/device/lock/associating_rooms/index.dart";
import "package:ct_pa_majordomo/pages/device/lock/detail/lock_detail_notifier.dart";
import "package:ct_pa_majordomo/state/common.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/widgets/button/tap_container.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:provider/provider.dart";

class LockInfo extends StatefulWidget {
  final LockDetailNotifier controller;
  final Function(bool update) onchange;
  const LockInfo({super.key, required this.controller, required this.onchange});


  @override
  State<StatefulWidget> createState() => _LockInfoState();

}

class _LockInfoState extends State<LockInfo> {
  late final LockDetailNotifier _controller = widget.controller;

  Map _roomInfo = {};
  Map _info = {};
  Map _lockInfo = {};
  Map _updateLockInfo = {};

  void _getRoomInfo(int roomId) async {
    if (roomId != null && roomId != -1) {
      Map resData = await apartmentApi.getRoomInfo(roomId);
      print(resData);
      setState(() {
        _roomInfo = resData["data"];
      });
    }
  }

  void _syncLock() async {
    EasyLoading.show();
    await lockApi.syncLock(int.parse(_info["lockId"]));
    widget.onchange(true);
    EasyLoading.dismiss();
  }

  @override
  void initState() {
    _controller.addListener(() {
      if (mounted) {
        setState(() {
          _info = _controller.info;
          print("的空间离开家：》》》》》》》》》》》$_info");
          _lockInfo = _info["lockInfo"] != null ? jsonDecode(_info["lockInfo"] ?? "") : {};
          print("sssss>>>>>>>>>>>>>>>>>>$_lockInfo");
          _getRoomInfo(_info["roomId"]);
        });
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return DecoratedBox(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        boxShadow: const [ThemeVars.boxShadow],
        color: Colors.white,
      ),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Consumer<CommonState>(builder: (context, notifier, child) {
                  return Text("${notifier.lockInfo?["lockAlias"] ?? ""}", style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600, ),);
                })
              ],
            ),
            const SolidDivider(padding: EdgeInsets.symmetric(vertical: 16), color: ThemeVars.colorBorder,),
            Row(
              children: [
                const Text("关联房间："),
                TapContainer(
                  onTap: () {
                    Navigator.push(
                      context,
                      CupertinoPageRoute(
                        builder: (BuildContext context) {

                          return AssociatedRoom(
                            lockId: int.parse(_info["lockId"]),
                            // roomId: -1,
                            roomId: _info["roomId"] ?? -1,
                          );
                        },
                      ),
                    ).then((needRefresh) {
                      if (needRefresh != null) {
                        setState(() {
                          _controller.setNeedRefresh(needRefresh);
                        });
                      }
                    });
                  },
                  child: _info["roomId"] == -1
                    ? const Text("去关联", style: TextStyle(color: ThemeVars.colorPrimary),)
                    : Text(_roomInfo["name"] ?? "", style: TextStyle(color: ThemeVars.colorPrimary),)
                ),
              ],
            ),
            const SizedBox(height: 8,),
            Row(
              children: [
                Text("电池电量："),
                Text("${_lockInfo["electricQuantity"]}%"),
              ],
            ),
            const SizedBox(height: 8,),
            Row(
              children: [
                const Text("更新时间："),
                Text(DateTools.formatYMD(_lockInfo["lockUpdateDate"], format: "{y}-{m}-{d} {h}:{i}")),
                const SizedBox(width: 8,),
                GestureDetector(
                  onTap: () {
                    /* 更新门锁数据 */
                    _syncLock();
                  },
                  child: const Text("更新", style: TextStyle(color: ThemeVars.colorPrimaryDark),),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

}